/**
 * 
 */
package com.mh.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mh.domain.Customer;
import com.mh.domain.Product;
import com.mh.service.ProductService;
import com.mh.web.utils.CustomGenericResponse;
import com.mh.web.utils.Page;

/**
 * @author VIT AUTO-GEN
 *
 */

@Controller
@RequestMapping(value="/product" )
public class ProductController {

	@Autowired
	ProductService productService;
	
	private Validator validator;
	
	/**
	 * 
	 */
	@Autowired
	public ProductController(Validator validator) {
		this.validator = validator;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getPage(){
		return "product";
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Product read(@PathVariable("id") Integer id){
		return productService.findProductByPrimaryKey(id);		
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody Page<Product> listProducts(Product product){
		List<Product> list = new ArrayList<Product>(productService.findProducts(product));
		Page<Product> pg = new Page<Product>();
		
		pg.setRows(list);

		return pg;
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.PUT)
	public @ResponseBody CustomGenericResponse delete(@PathVariable("id") int id){
		CustomGenericResponse resp = new CustomGenericResponse();
		try {
			Product product = productService.findProductByPrimaryKey(id);
			productService.deleteProduct(product);
			resp.setSuccess(true);
			resp.setMessage("Success");
		} catch (Exception e) {
			resp.setSuccess(true);
			resp.setMessage("Error");
		}		
		return resp;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
	public @ResponseBody CustomGenericResponse  update(
			@RequestBody Product product, @PathVariable("id") int id){
		CustomGenericResponse resp = new CustomGenericResponse();
		
		if(product != null){
			product.setModifiedBy(getUser());
			product.setModifiedOn(new Date());
		}
		
		List<String> errors = validate(product);
		if(!errors.isEmpty()){
			resp.setSuccess(false);			
			resp.setMessages(errors);
			return resp;
		}		
		productService.saveProduct(product);
		return resp;
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.PUT)	
	public @ResponseBody CustomGenericResponse  save(
			@RequestBody Product product){
		CustomGenericResponse resp = new CustomGenericResponse();
		if(product != null){
			product.setCreatedBy(getUser());
			product.setCreatedOn(new Date());
		}
		
		List<String> errors = validate(product);
		if(!errors.isEmpty()){
			resp.setSuccess(false);			
			resp.setMessages(errors);
			return resp;
		}
		productService.saveProduct(product);
		return resp;
	}
	
	private List<String> validate(Product product){
		List<String> errors = new ArrayList<String>();
		Set<ConstraintViolation<Product>> violations = validator.validate(product);
		for (ConstraintViolation<Product> violation : violations) 
			errors.add(violation.getPropertyPath() + " " + violation.getMessage());			   
		return errors;		
	}
	
	private String getUser(){
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String userName ="";
        if ( obj instanceof UserDetails ) {
                userName= ( (UserDetails)obj ).getUsername();
        } else {
                userName = obj.toString();
        }
        return userName;
	}
	
}
